package com.example.ymm.modules1.service.dkn;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.ymm.modules1.entity.hl.dkn.DknProductMapping;
import com.example.ymm.modules1.entity.hl.dkn.DknPurchaseOrder;
import com.example.ymm.modules1.query.hl.DknProductMappingQueryCriteria;
import com.example.ymm.modules1.query.hl.DknPurchaseOrderQueryCriteria;
import com.example.ymm.modules1.service.dto.dkn.DknEditOrderDto;
import com.example.ymm.modules1.service.dto.heng.DknCreatePurchaseOrderGroupDto;
import com.example.ymm.modules1.service.dto.heng.DknProductMappingDto;
import com.example.ymm.modules1.service.dto.ms.MsOrderDto;
import com.example.ymm.modules1.service.dto.ms.MsOrderListQueryCriteria;
import com.example.ymm.modules1.service.hl.DknProductMappingService;
import com.example.ymm.modules1.service.hl.DknPurchaseOrderService;
import com.example.ymm.modules1.service.ms.TProviderPartnerService;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.EmailUtil;
import com.example.ymm.util.UtilValidate;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;



/**
 * 迪卡侬业务类
 */
@Slf4j
@Service
public class DknOrderService {

    @Value("${dkn.domain}")
    private String domain;
    @Autowired
    DknAccessTokenService dknAccessTokenService;
    @Autowired
    DknPurchaseOrderService purchaseOrderService;
    @Autowired
    TProviderPartnerService tProviderPartnerService;

    @Autowired
    DknProductMappingService dknProductMappingService;

    /**
     * 创建防盗贴纸订单
     * @return
     */
    public JsonNode postCreateCarelabelOrder(JSONObject param) {
        String url=domain+"/v1/orders/inquiries/carelabel/creation";

        return dknAccessTokenService.postJson(url,param);
    }


    /**
     * 创建 配件 订单
     * @return
     */
    public JsonNode postCreateComponentOrder(JSONObject param) {
        String url=domain+"/v1/orders/inquiries/component/creation";

        return dknAccessTokenService.postJson(url,param);
    }

    /**
     * 取消订单
     * @param order_code
     * @return
     */
    public JsonNode postCancelOrder(String order_code){
        String url=domain+"/v1/orders/"+order_code+"/cancellation";
        JSONObject param=new JSONObject();
        param.put("order_code",order_code);
        return dknAccessTokenService.postJson(url,param);
    }


    public JsonNode getLines(String order_code) {
        String url=domain+"/v1/orders/"+order_code+"/lines";

        return dknAccessTokenService.getJson(url,null);
    }


    /**
     * 修改订单项
     * @param
     * @return
     */
    public JsonNode postEditItem(DknEditOrderDto dto){
        String url=domain+"/v1/orders/"+dto.getOrderCode()+"/lines/"+dto.getLine_number();
        JSONObject param=new JSONObject();
        param.put("quantity",dto.getQuantity());
        param.put("conception_code",dto.getConception_code());
        param.put("comment",dto.getComment());
        return dknAccessTokenService.postJson(url,param);
    }

    /**
     * 添加 订单项
     * @param
     * @return
     */
    public JsonNode postAddItem(DknEditOrderDto dto){
        String url=domain+"/v1/orders/"+dto.getOrderCode()+"/lines/"+dto.getLine_number();
        JSONObject param=JSONObject.parseObject(JSONObject.toJSONString(dto));
        param.put("shipment_method","ROAD");
        return dknAccessTokenService.postJson(url,param);
    }

    /**
     * 删除 订单项
     * @param
     * @return
     */
    public JsonNode postRemoveItem(DknEditOrderDto dto){
        String url=domain+"/v1/orders/"+dto.getOrderCode()+"/lines/"+dto.getLine_number();
        return dknAccessTokenService.deleteJson(url);
    }

    public JsonNode getOrders(String date) {
        JSONObject param=new JSONObject();
        if(UtilValidate.isNotEmpty(date)){
            param.put("date", URLEncoder.encode(date));
        }
        String url=domain+"v1/orders";
        param.put("vendor_cnuf", "77374");
        return dknAccessTokenService.getJson(url,param);
    }

    public JsonNode getOrderDetail(String orderCode){
        JSONObject param=new JSONObject();
        String url=domain+"v1/orders/"+orderCode;

        return dknAccessTokenService.getJson(url,null);
    }


    /**
     * 查询订单
     * @param inquiryCode
     * @return
     */
    public JsonNode inquiriesOrder(String inquiryCode){

        String url=domain+"v1/orders/inquiries/"+inquiryCode;

        return dknAccessTokenService.getJson(url,null);
    }


    /**
     * 验证订单
     * @param orderCode
     * @return
     */
    public JsonNode validationOrder(String orderCode){

        String url=domain+"v1/orders/"+orderCode+"/validation";

        return dknAccessTokenService.postJson(url,new JSONObject());
    }


    public JsonNode extraFeatures(String provider_cnuf,String item_code){
        String url=domain+"/v1/catalog/"+provider_cnuf+"/"+item_code+"/extra_features";
        JSONObject param=new JSONObject();
        param.put("provider_cnuf", provider_cnuf);
        param.put("item_code", item_code);
        param.put("vendor_dpp_code", "2153");
        return dknAccessTokenService.getJson(url,param);
    }


    /**
     * 健康检查
     * @return
     */
    public JsonNode healthPing(){
        String url=domain+"/v1/health/ping";
        return dknAccessTokenService.getJson(url,null);
    }

    /**
     * 获取 配件订单
     * @return
     */
    public List<DknCreatePurchaseOrderGroupDto> getMsComponentLianShenOrderList(String orderNo){
        List<String> supplierNoIn=new ArrayList<>();

        /**
         * GYS0003  漳州市_福建华发包装有限公司
         * GYS0010  厦门市_联盛(厦门)彩印有限公司
         */

//        supplierNoIn.add("GYS0003");
        supplierNoIn.add("GYS0010");
        return getMsBaseOrderList(supplierNoIn,orderNo);
    }

    /**
     * 获取 配件订单
     * @return
     */
    public List<DknCreatePurchaseOrderGroupDto> getMsComponentHuaFaOrderList(String orderNo){
        List<String> supplierNoIn=new ArrayList<>();

        /**
         * GYS0003  漳州市_福建华发包装有限公司
         * GYS0010  厦门市_联盛(厦门)彩印有限公司
         */

        supplierNoIn.add("GYS0003");
//        supplierNoIn.add("GYS0010");
        return getMsBaseOrderList(supplierNoIn,orderNo);
    }

    /**
     * 获取 防盗贴纸订单
     * @return
     */
    public List<DknCreatePurchaseOrderGroupDto> getMsCarelabelOrderList(String orderNo){
        List<String> supplierNoIn=new ArrayList<>();
        // 艾利  GYS0034
        supplierNoIn.add("GYS0034");

        return getMsBaseOrderList(supplierNoIn,orderNo);
    }

    public List<DknCreatePurchaseOrderGroupDto> getMsBaseOrderList(List<String> supplierNoIn,String orderNo){
        DknPurchaseOrderQueryCriteria criteria=new DknPurchaseOrderQueryCriteria();

        criteria.setOrderNo(orderNo);
        criteria.setSupplierNoIn(supplierNoIn);
//        Date t_day = new Date();
//        Date now=DateKit.dateAdd(1,t_day,3);
//        String orderDateStart= DateKit.dateFormat(now,"yyyy-MM-dd 00:00:00");
//        String orderDateStart= DateKit.dateFormat(t_day,"yyyy-MM-dd 00:00:00");
//        criteria.setOrderDateStart(orderDateStart);
        List<DknCreatePurchaseOrderGroupDto> list = purchaseOrderService.purchaseOrderWaitList(criteria);
        for(DknCreatePurchaseOrderGroupDto dto:list){
            MsOrderListQueryCriteria c=new MsOrderListQueryCriteria();
            c.setSupplierNo(dto.getSupplierNo());
            c.setOrderNo(dto.getOrderNo());
           // c.setOrderDateStart(orderDateStart);
            List<DknProductMappingDto> msOrderDtos = dknProductMappingService.purchaseOrderList(c);
            MsOrderListQueryCriteria c2=new MsOrderListQueryCriteria();
            c2.setOrderNo(dto.getOrderNo());
            String requestDate=dknProductMappingService.purchaseOrderListMaxTime(c2);//交期
//            if(UtilValidate.isNotEmpty(msOrderDtos)){
//                for(DknProductMappingDto item: msOrderDtos){
//                    if(UtilValidate.isNotEmpty(item.getRequestDate())){
//                        requestDate=item.getRequestDate();
//                    }
//                }
//            }
            dto.setRequestDate(requestDate);
            dto.setItems(msOrderDtos);
        }
        return list;
    }


    public List<DknCreatePurchaseOrderGroupDto> getMyOrderList(String orderNo){
        Date now=DateKit.getAddDayDate(new Date(),10);
        String date= DateKit.dateFormat(now);
        List<DknCreatePurchaseOrderGroupDto> list = new ArrayList<>();
        DknCreatePurchaseOrderGroupDto groupDto=new DknCreatePurchaseOrderGroupDto();
        groupDto.setOrderNo(orderNo);
        groupDto.setRequestDate(date);
        groupDto.setCurrency("人民币");
        list.add(groupDto);
        for(DknCreatePurchaseOrderGroupDto dto:list){

            DknProductMappingQueryCriteria pm=new DknProductMappingQueryCriteria();
            // 0405060024 联盛

            pm.setMtid("0405060024");
            List<DknProductMapping> msOrderDtos = dknProductMappingService.queryAll(pm);
            String requestDate=date;//交期
            List<DknProductMappingDto> dts=new ArrayList<>();
            if(UtilValidate.isNotEmpty(msOrderDtos)){
                for(DknProductMapping item: msOrderDtos){
                    DknProductMappingDto productMappingDto=new DknProductMappingDto();
                    BeanUtils.copyProperties(item, productMappingDto);
                    productMappingDto.setRequestDate(requestDate);
                    productMappingDto.setRemark("迪卡侬");
                    productMappingDto.setQuantity(10000);
                    dts.add(productMappingDto);
                }
            }
            dto.setRequestDate(requestDate);
            dto.setItems(dts);
        }
        return list;
    }



    /**
     *
     * @param dto
     * @param type  配件订单 component   防盗贴纸 carelabel
     * @return
     */
    public JSONObject getMsDataJson(DknCreatePurchaseOrderGroupDto dto,String type) {
        JSONObject obj=new JSONObject();
        obj.put("vendor_cnuf","77374");
        obj.put("vendor_dpp_code","2153");//90536,2153
        String currency="";
        if("人民币".equals(dto.getCurrency())){
            currency="CNY";
        }else if("美元".equals(dto.getCurrency())){
            currency="USD";
        }
       // obj.put("orderNo",dto.getOrderNo());
        obj.put("currency",currency);
        JSONObject header=new JSONObject();
        header.put("internal_code",dto.getOrderNo());//单号
        header.put("note",dto.getRemark());//备注
        header.put("billing_address_code","502263");//502263 245981
        header.put("shipping_address_code","502261");//502261 435400
        header.put("requested_ship_date",dto.getRequestDate());//交期
        obj.put("header",header);
        List<JSONObject> lines=new ArrayList<>();
        for(DknProductMappingDto item:dto.getItems()){
            JSONObject line=new JSONObject();

            line.put("incoterm",item.getIncoterm());
            line.put("shipment_method","ROAD");
            line.put("comment",item.getRemark());
            line.put("quantity",item.getQuantity());
            line.put("conception_code",item.getCodeCc());//成衣CC号
            line.put("provider_cnuf",item.getSupplierCode());//物料供应商代码，由CCS部门提供
        //    line.put("unit","pcs");//item.getUnit()
            if("component".equals(type)){
                line.put("component_reference",item.getItemCode());//迪卡侬物料item code
            }
            if("carelabel".equals(type)){
                line.put("finished_good_item_code",item.getItemCode());//迪卡侬物料item code
            }
            lines.add(line);
        }
        obj.put("lines",lines);
        return obj;
    }

    /**
     * 创建贴纸订单
     */
    public void createCarelabelOrderFn(String orderNo){
        List<DknCreatePurchaseOrderGroupDto> msCarelabelOrderList = getMsCarelabelOrderList(orderNo);
        String type="carelabel";
        for(DknCreatePurchaseOrderGroupDto orderGroup:msCarelabelOrderList){
            JSONObject json = getMsDataJson(orderGroup, type);
            System.out.println("---请求参数");
            System.out.println(json);
            JsonNode jsonNode = postCreateCarelabelOrder(json);
            json.put("orderNo",orderGroup.getOrderNo());
            System.out.println("---相应");
            System.out.println(jsonNode);
            operatorSaveRespondData(jsonNode,type,json,"rfid");
        }


    }




    public void createCarelabelOrderFnTest1(){
//        List<DknCreatePurchaseOrderGroupDto> msCarelabelOrderList = getMsCarelabelOrderList();
//        String type="carelabel";
//        List<JSONObject> list = getMsDataJson(msCarelabelOrderList, type);
//        JsonNode jsonNode = postCreateCarelabelOrder(list.get(0));

    }

    /**
     * 创建配件订单
     */
    public void createMyComponentFn(String orderNo){
        List<DknCreatePurchaseOrderGroupDto> OrderList = getMyOrderList(orderNo);
        String type="component";
        for(DknCreatePurchaseOrderGroupDto orderGroup:OrderList){
            JSONObject json= getMsDataJson(orderGroup, type);
            System.out.println("--配件订单请求参数");
            System.out.println(json);
            JsonNode jsonNode =postCreateComponentOrder (json);
            json.put("orderNo",orderGroup.getOrderNo());
            System.out.println("--配件订单响应");
            System.out.println(jsonNode);
            operatorSaveRespondData(jsonNode,type,json,null);
        }
    }

    /**
     * 处理和保存响应数据
     * @param
     */
    public void operatorSaveRespondData(JsonNode node,String type,JSONObject param,String remark){
        if(node.has("error")){
            log.error("--迪卡侬同步采购单异常:"+node.asText());
            EmailUtil.sendEmail("1055162826@qq.com","迪卡侬同步采购单异常:",node.path("error_description").asText());
        }else{

            String orderNo = param.getString("orderNo");
            DknPurchaseOrder purchaseOrder=new DknPurchaseOrder();
            purchaseOrder.setOrderNo(orderNo);
            String inquiry_code= node.get("inquiry_code").asText();
//            String inquiry_date= node.get("inquiry_date").asText();
            String inquiry_status= node.get("inquiry_status").asText();

            purchaseOrder.setType(type);
            purchaseOrder.setInquiryCode(inquiry_code);
            purchaseOrder.setInquiryStatus(inquiry_status);
//            purchaseOrder.setInquiryDate(inquiry_date);
            purchaseOrder.setParameter(param.toJSONString());
            purchaseOrder.setBody(node.asText());
            purchaseOrder.setNote(remark);
            purchaseOrderService.save(purchaseOrder);
        }
    }





    /**
     * 创建 自定义配件订单 -联盛
     */
    public void createComponentOrderLianShenFn(String orderNo){
        List<DknCreatePurchaseOrderGroupDto> OrderList = getMsComponentLianShenOrderList(orderNo);
        String type="component";
        for(DknCreatePurchaseOrderGroupDto orderGroup:OrderList){
            if(UtilValidate.isNotEmpty(orderGroup.getItems())){
                JSONObject json= getMsDataJson(orderGroup, type);
                System.out.println("--配件订单请求参数");
                System.out.println(json);
                JsonNode jsonNode =postCreateComponentOrder (json);
                json.put("orderNo",orderGroup.getOrderNo());
                System.out.println("--配件订单响应");
                System.out.println(jsonNode);
                operatorSaveRespondData(jsonNode,type,json,"厦门_联盛");
            }

        }
    }

    /**
     * 创建 自定义配件订单 -漳州市_福建华发
     */
    public void createComponentOrderHuaFaFn(String orderNo){
        List<DknCreatePurchaseOrderGroupDto> OrderList = getMsComponentHuaFaOrderList(orderNo);
        String type="component";
        for(DknCreatePurchaseOrderGroupDto orderGroup:OrderList){
            if(UtilValidate.isNotEmpty(orderGroup.getItems())){
                JSONObject json= getMsDataJson(orderGroup, type);
                System.out.println("--配件订单请求参数");
                System.out.println(json);
                JsonNode jsonNode =postCreateComponentOrder (json);
                json.put("orderNo",orderGroup.getOrderNo());
                System.out.println("--配件订单响应");
                System.out.println(jsonNode);
                operatorSaveRespondData(jsonNode,type,json,"漳州_华发");
            }

        }
    }


}
